import { objectToString } from "../../utils";
import type { BaseResource } from "./types";

const baseK8sPath = "/api/v1/kubeHud/k8s";

export const sourceUrl = (src: string, ns?: string, query?: any): string => {
  let path = `${baseK8sPath}`;
  if (ns) {
    path += `/namespaces/${ns}`;
  }
  path += `/${src}`;
  if (query) {
    path += "?" + objectToString(query, "&");
  }
  return path;
};

export type MergePathReq<T = any> = MakePathReq &
  BaseResource & {
    data?: T;
  };

export type MakePathReq = {
  src?: string; // 资源(s), pods/nodes/services ...
  app?: string;
  srcName?: string; // 资源名称
  namespace?: string; // 命名空间
  cluster?: string; // 集群
  operation?: string; // 操作 log/exec/terminal/eviction...
  query?: {
    fieldSelector?: string;
    labelSelector?: string;
    [key: string]: any;
  }; // 查询参数
};
export const k8sPath = (arg: MakePathReq): string => {
  let path = `${baseK8sPath}`;

  // 集群
  if (arg.cluster && arg.cluster !== "") {
    path += `/clusters/${arg.cluster}`;
  }

  // 命名空间
  if (arg.app === "") {
    path += `/api/v1`;
  } else {
    path += `/apis/${arg.app ?? "apps/v1"}`;
  }

  if (arg.namespace && arg.namespace !== "") {
    path += `/namespaces/${arg.namespace}`;
  }

  // 资源
  path += `/${arg.src}`;

  // 资源名称
  if (arg.srcName) {
    path += `/${arg.srcName}`;
  }

  // 操作
  if (arg.operation) {
    path += `/${arg.operation}`;
  }

  //容错
  path = path.replaceAll("//", "/");

  // 查询参数
  // if (arg.query) {
  //   path += "?" + objectToString(arg.query, "&");
  // }

  return path;
};

export const k8sPathMergeReqs = (...args: MergePathReq[]): string => {
  let req: MakePathReq = {};
  for (const r of args) {
    if (!r) continue;
    if (r.metadata && r.apiVersion) {
      if (r.metadata?.name) {
        req.srcName = r.metadata?.name;
      }
      if (r.metadata?.namespace) {
        req.namespace = r.metadata.namespace;
      }
    } else {
      req = Object.assign(req, r); //{ ...req, ...r };
    }
  }

  return k8sPath(req);
};

export const k8sBasePath = (cluster: string, subPaths: string): string => {
  return `${baseK8sPath}/clusters/${cluster}/${subPaths}`.replaceAll("//", "/");
};

// clusters/default/apis/apps/v1/namespaces/default/deployments
//                  apis/apps/v1/namespaces/default/deployments
